import VXETable from 'vxe-table'
import intersection from 'lodash/intersection'
import isNil from 'lodash/isNil'
import createBem from '@Components/assets/js/utils/bem'
import { tableNamespace } from '../../../config'
import './index.scss'

const Bem = createBem(`${tableNamespace}__filter-select`)

VXETable.renderer.add('Select', {
  // showFilterFooter: false,
  renderFilter(h, renderOpts, { column, $panel }) {
    /**
     *@type { { list: Array<{ label: string; value: string; }> } }
     */
    const { list = [], options = {}, $tableInstance } = renderOpts
    let renderList = list
    if (typeof list === 'string') {
      renderList = $tableInstance?.selectOptionsList?.[list]?.list || []
    }
    const { multiple } = options
    const filters = column.filters[0]

    function handleChange(value) {
      filters.data = value
      const checked = multiple
        ? filters.data && filters.data.length > 0
        : !isNil(filters.data)
      $panel.changeOption(null, checked, filters)
    }
    function handleVisibleChange(isShow) {
      if (!isShow) {
        $panel.confirmFilter()
      }
    }
    return [
      <div class={Bem()}>
        <el-select
          value={filters.data}
          size={this.$store.getters.size}
          props={options}
          onChange={handleChange}
          onVisible-change={handleVisibleChange}
        >
          {renderList.map(i => (
            <el-option key={i.value} value={i.value} label={i.label} />
          ))}
          <el-option key="null" value="null" label="--" />
        </el-select>
      </div>
    ]
  },
  filterMethod(params) {
    const { option, row, column } = params
    const { data } = option
    const { filterRender: renderOpts } = column
    const { options = {} } = renderOpts
    const cellValue = row[column.property]
    if (cellValue === null && data.includes('null')) {
      return true
    }

    if (options.multiple) {
      if (Array.isArray(cellValue)) {
        if (cellValue.length === 0 && data.includes('null')) {
          return true
        }
        return intersection(cellValue, data).length
      }
      return data.indexOf(cellValue) > -1
    }
    return cellValue === data
  }
})
